name: Deploy Nightly Release
on:
  schedule:
    - cron: '0 2 * * *' # run at 2 AM UTC

jobs:
  build:
    if: github.repository == 'backstage/backstage' # prevent running on forks

    runs-on: ubuntu-latest

    env:
      CI: true
      NODE_OPTIONS: --max-old-space-size=8192

    steps:
      - name: Harden Runner
        uses: step-security/harden-runner@63c24ba6bd7ba022e95695ff85de572c04a18142 # v2.7.0
        with:
          egress-policy: audit

      - uses: actions/checkout@b4ffde65f46336ab88eb53be808477a3936bae11 # v4.1.1

      - name: use node.js 18.x
        uses: actions/setup-node@60edb5dd545a775178f52524783378180af0d1f8 # v4.0.2
        with:
          node-version: 18.x
          registry-url: https://registry.npmjs.org/ # Needed for auth
      - name: yarn install
        uses: backstage/actions/yarn-install@a674369920067381b450d398b27df7039b7ef635 # v0.6.5
        with:
          cache-prefix: ${{ runner.os }}-v18.x

      # No verification done here, only build & publish. If the master branch
      # is broken we will see that from those builds, but we still want to push nightly
      # builds since upgrading to them is a manual process anyway.

      - name: tsc
        run: yarn tsc

      - name: build
        run: yarn backstage-cli repo build

      - name: build embedded techdocs app
        working-directory: packages/techdocs-cli-embedded-app
        run: yarn build

      # Prepares a nightly release version of any package with pending changesets
      # Pre-mode is exited if case we're in it, otherwise it has no effect
      - name: prepare nightly release
        run: |
          yarn changeset pre exit || true
          yarn changeset version --snapshot nightly

      # Publishes the nightly release to npm, by using tag we make sure the release is
      # not flagged as the latest release, which means that people will not get this
      # version of the package unless requested explicitly
      - name: publish nightly release
        run: |
          yarn config set -H 'npmAuthToken' "${{secrets.NPM_TOKEN}}"
          yarn workspaces foreach -p -j 10 -v --no-private npm publish --access public --tolerate-republish --tag nightly
        env:
          NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }}

      - name: Discord notification
        if: ${{ failure() }}
        uses: Ilshidur/action-discord@0c4b27844ba47cb1c7bee539c8eead5284ce9fa9 # 0.3.2
        env:
          DISCORD_WEBHOOK: ${{ secrets.DISCORD_WEBHOOK }}
        with:
          args: 'Nightly build failed https://github.com/{{GITHUB_REPOSITORY}}/actions/runs/{{GITHUB_RUN_ID}}'
